package com.zlx.xBiaoShop.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.kaptcha.Kaptcha;
import com.zlx.xBiaoShop.entity.Result;
import com.zlx.xBiaoShop.entity.User;
import com.zlx.xBiaoShop.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.*;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
* @Description user 控制器层
* @author admin
* @date 2020-12-05 17:52:12
*/
@RestController
@CrossOrigin
@RequestMapping("/user")
public class UserController{
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private Kaptcha kaptcha;



    @PutMapping("forget/{code}")
    public Result forget(@RequestBody User user, @PathVariable("code") String code){
        //获取验证码
        String check = (String) redisTemplate.opsForValue().get("com.zlx.xbhy.service.impl.IMailServiceImpl:" + user.getEmail());
        User exitsUser = new User();
        //错误提示信息
        String msg=null;
        //用户是否存在
        if (user!=null&&user.getUsername()!=null){
            exitsUser=userService.isExists(user.getUsername());
            if (exitsUser!=null) {   //用户邮箱存在
                if (code.equals(check)) {//验证码正确
                    if (user.getEmail()!=null) {
                        userService.updatePassword(user.getUsername(), user.getPassword());
                        return new Result(true, "修改密码成功！",null);
                    }else {
                        msg="密码不能为空";
                    }
                }else {
                    msg="用户验证码错误，请审核后再填写！！！";
                }
            }else {
                msg="用户名不存在，请确认后再填写！！！";
            }
        }else {
            msg="用户名不能为空";
        }

        return new Result(false,msg,null);
    }
    /**
     * @Author Edward
     * @Description 登录的页面
     * @Date 22:31 2020/11/17
     * @Param [username, password, code]
     * @return com.zlx.xbhy.entity.Result
     **/
    @PostMapping("/login/{remberMe}/{code}")
    public Result login(@PathVariable Boolean remberMe,@RequestBody User user, @PathVariable String code,
                        HttpSession session, HttpServletResponse response){
        String message = null;
        if (StringUtils.isEmpty(code)){
            message="验证码不能为空！";
        }else {
            if (kaptcha.validate(code)) {//验证码正确
                user = userService.findUerByUsernameAndPassword(user.getUsername(),user.getPassword());
                if (!StringUtils.isEmpty(user)) {//用户名正确
                    if (remberMe){
                        //免密码登陆
                        String encodeCookie = URLEncoder.encode(JSONObject.toJSONString(user));
                        Cookie cookie = new Cookie("loginUser", encodeCookie);
                        cookie.setPath("/");
                        //最大7天
                        cookie.setMaxAge(60*60*24*7);
                        response.addCookie(cookie);
                    }
                    //置空密码
                    user.setPassword(null);
                    session.setAttribute("loginUser",user);
                    return new Result(user);
                }
            } else {
                //验证码错误
                message = "验证码错误";
            }
        }
        return new Result(false,message,null);
    }
    //修改默认地址
    @PutMapping("changeDefalutAddr/{userId}/{addrId}")
    public Result ChangeDefalutAddr(@PathVariable Integer userId,@PathVariable Integer addrId){
        userService.changeDefalutAddr(userId,addrId);
        return new Result("默认地址修改完成");
    }
    /*
        修改用户的信息
     */
    @PostMapping("updateUserInfo")
    public Result updateUserInfo(@RequestBody User user,HttpSession session){
        userService.updateUserInfo(user);
        session.setAttribute("loginUser",user);
        return new Result(true,"用户信息完成！",null);
    }

    @GetMapping("getUserInfo")
    public Result getUserInfo(HttpSession session, HttpServletRequest request) throws UnsupportedEncodingException {
        User user = (User) session.getAttribute("loginUser");
        if (user==null){
            Cookie[] cookies = request.getCookies();
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                if ("loginUser".equals(name)) {
                    String value =  URLDecoder.decode(cookie.getValue() , "utf-8");
                    user=JSONObject.parseObject(value,User.class);
                }
            }
        }
        return new Result(user);
    }
    @PostMapping("register")
    public Result register(@RequestBody User user){
        user.setSex("0");
        user.setPic("http://thirdqq.qlogo.cn/g?b=oidb&k=d8gJTWcG55qDicUejicRlURw&s=100&t=1585930084");
        User save = userService.save(user);
        return new Result("注册成功！");
    }
    @GetMapping("getbyUsername/{username}")
    public Result getbyUsername(@PathVariable String username){
        User user = userService.getbyUsername(username);
        if (user!=null){
            return new Result(true,"用户已存在！！！",null);
        }
        return new Result(false,"用户不存在",null);
    }
    //退出登录
    @GetMapping("exitLogin")
    public Result exitLogin(HttpServletRequest request,HttpServletResponse response){
        request.getSession().removeAttribute("loginUser");
        Cookie loginUser = new Cookie("loginUser", "");
        loginUser.setMaxAge(0);
        loginUser.setPath("/");
        response.addCookie(loginUser);
        return new Result("退出登录成功！");
    }
}
